<template>
  <div>
    <el-row :gutter="20">
      <splitpanes class="default-theme">
        <!--文件数据-->
        <!--文件数据-->
        <pane size="16">
          <div>
            <el-scrollbar height="82vh">
              <el-col>
                <div class="head-container">
                  <el-input
                    v-model="coltName"
                    clearable
                    placeholder="请输入栏目名称"
                    prefix-icon="Search"
                    style="margin-bottom: 20px"
                  />
                </div>
                <div>
                  <el-tree
                    :data="treeDataWithTop"
                    :props="defaultProps"
                    ref="deptTreeRef"
                    node-key="id"
                    highlight-current
                    @node-click="handleNodeClick"
                    :filter-node-method="filterNode"
                  />
                </div>
              </el-col>
            </el-scrollbar>
          </div>
        </pane>
        <!-- 表单部分 -->
        <pane size="84">
          <el-col>
            <el-card>
              <el-form
                :inline="true"
                :model="searchForm"
                class="demo-form-inline"
                label-width="100px"
                label-position="right"
              >
                <el-row>
                  <el-col :span="7">
                    <el-form-item label="ID">
                      <el-input
                        v-model="searchForm.queryId"
                        placeholder="请输入ID"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item label="标题">
                      <el-input
                        v-model="searchForm.queryTitle"
                        placeholder="请输入标题"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item label="类型">
                      <el-select
                        v-model="searchForm.queryTypeId"
                        placeholder="请选择类型"
                        clearable
                        :style="selectWidth"
                      >
                        <el-option
                          v-for="item in typeList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="7">
                    <el-form-item label="发布者">
                      <el-input
                        v-model="searchForm.queryInputUsername"
                        placeholder="请输入发布者"
                        clearable
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="预约发布时间">
                      <el-date-picker
                        type="date"
                        v-model="searchForm.releaseDate"
                        placeholder="请选择预约发布时间"
                        clearable
                        :style="selectWidth"
                        style="width: 200px"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="7">
                    <el-form-item label="状态">
                      <el-select
                        v-model="searchForm.queryStatus"
                        placeholder="请选择状态"
                        clearable
                        :style="selectWidth"
                      >
                        <el-option label="草稿" value="draft" />
                        <el-option label="待审" value="prepared" />
                        <el-option label="终审" value="checked" />
                        <el-option label="退回" value="rejected" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col>
                    <el-form-item label="是否校对">
                      <el-select
                        v-model="searchForm.checkstatus"
                        placeholder="请选择"
                        clearable
                        :style="selectWidth"
                        style="width: 200px"
                      >
                        <el-option label="未校对" value="0" />
                        <el-option label="已校对" value="1" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row class="buttons">
                  <el-col>
                    <el-form-item>
                      <el-button type="primary" @click="onSearch" size="small"
                        ><el-icon><Search /></el-icon>&nbsp;搜索</el-button
                      >
                      <el-button @click="onReset" size="small"
                        ><el-icon><Refresh /></el-icon>&nbsp;重置</el-button
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-card>
            <!-- 表格部分 -->
            <el-card style="margin-top: 10px">
              <div style="margin-bottom: 5px">
                <el-button
                  type="primary"
                  plain
                  @click="handleAdd"
                  size="small"
                  v-if="isCreateRole"
                  ><el-icon><Plus /></el-icon>添加</el-button
                >
                <el-button
                  type="success"
                  plain
                  @click="handleSubmit"
                  size="small"
                  :disabled="multiple"
                  v-if="isSubmitRole"
                  ><el-icon><Upload /></el-icon>提交</el-button
                >
                <!-- <el-button
                  type="info"
                  plain
                  @click="handleProofread"
                  size="small"
                  :disabled="multiple"
                  ><el-icon><Check /></el-icon>校对</el-button
                > -->
                <el-button
                  type="success"
                  plain
                  @click="handlePass"
                  size="small"
                  :disabled="multiple"
                  v-if="isExamineRole"
                  ><el-icon><DocumentChecked /></el-icon>审核通过</el-button
                >
                <el-button
                  type="warning"
                  plain
                  @click="handleInstance"
                  size="small"
                  :disabled="multiple"
                  v-if="isInstanceRole"
                  ><el-icon><Checked /></el-icon>直接终审</el-button
                >
                <el-button
                  type="danger"
                  plain
                  @click="handleNopass"
                  size="small"
                  :disabled="multiple"
                  v-if="isExamineRole"
                  ><el-icon><DocumentDelete /></el-icon>审核不通过</el-button
                >
                <el-button
                  type="danger"
                  plain
                  @click="handleAllDelete"
                  size="small"
                  :disabled="multiple"
                  v-if="isDeleteRole"
                  ><el-icon><DeleteFilled /></el-icon>删除</el-button
                >
              </div>
              <el-table
                :data="tableData"
                style="width: 100%"
                @selection-change="handleSelectionChange"
                @sort-change="handleSortChange"
                @cell-click="copyCellContent"
              >
                <el-table-column type="selection" width="50" />
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column
                  prop="contentExt.title"
                  label="标题"
                  min-width="200"
                  show-overflow-tooltip
                >
                  <template #default="{ row }">
                    {{
                      row.contentExt ? processedTitle(row.contentExt.title) : ''
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="type.name" label="类型" width="80" />
                <el-table-column
                  prop="username"
                  label="发布者"
                  min-width="120"
                />
                <el-table-column prop="sortDate" label="发布时间" width="120">
                  <template #default="{ row }">
                    {{ dayjs(row.sortDate).format('YYYY-MM-DD') }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="releaseDateMain"
                  label="预约发布时间"
                  width="150"
                >
                  <template #default="{ row }">
                    {{ dayjs(row.releaseDateMain).format('YYYY-MM-DD') }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" min-width="80">
                  <template #default="{ row }">
                    <el-tag
                      v-if="row.status === 0"
                      :disable-transitions="true"
                      type="primary"
                      size="small"
                      >草稿</el-tag
                    >
                    <el-tag
                      v-else-if="row.status === 2"
                      :disable-transitions="true"
                      type="success"
                      size="small"
                      >已终审</el-tag
                    >
                    <el-tag
                      v-else-if="
                        row.status === 1 &&
                        row.contentCheckSet?.rejected === true
                      "
                      :disable-transitions="true"
                      type="danger"
                      size="small"
                      >已退回</el-tag
                    >
                    <el-tag
                      v-else-if="
                        row.status === 1 && row.contentCheckSet?.checkStep === 1
                      "
                      :disable-transitions="true"
                      type="info"
                      size="small"
                      >一级待审</el-tag
                    >
                    <el-tag
                      v-else-if="
                        row.status === 1 && row.contentCheckSet?.checkStep === 2
                      "
                      :disable-transitions="true"
                      type="warning"
                      size="small"
                      >二级待审</el-tag
                    >
                    <el-tag
                      v-else-if="
                        row.status === 1 && row.contentCheckSet?.checkStep === 3
                      "
                      :disable-transitions="true"
                      type="success"
                      size="small"
                      >三级待审</el-tag
                    >
                    <el-tag
                      v-else-if="
                        row.status === 1 && row.contentCheckSet?.checkStep > 3
                      "
                      :disable-transitions="true"
                      type="success"
                      size="small"
                      >已终审</el-tag
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  prop="checkstatus"
                  label="是否校对"
                  min-width="80"
                >
                  <template #default="{ row }">
                    <el-tag
                      v-if="row.checkstatus === 0"
                      :disable-transitions="true"
                      type="danger"
                      size="small"
                      >未校对</el-tag
                    >
                    <el-tag
                      v-if="row.checkstatus === 1"
                      :disable-transitions="true"
                      type="success"
                      size="small"
                      >已校对</el-tag
                    >
                  </template>
                </el-table-column>
                <el-table-column label="操作" min-width="240">
                  <template #default="{ row }">
                    <el-button
                      link
                      plain
                      type="primary"
                      size="small"
                      @click="onPreview(row)"
                      ><el-icon><View /></el-icon>查看</el-button
                    >
                    <el-button
                      link
                      plain
                      type="primary"
                      size="small"
                      @click="onEdit(row)"
                      :disabled="row.status !== 0"
                      ><el-icon><Edit /></el-icon>修改</el-button
                    >
                    <el-button
                      link
                      type="primary"
                      plain
                      @click="handleProofread(row)"
                      size="small"
                      :disabled="row.checkstatus === 1"
                      ><el-icon><Check /></el-icon>校对</el-button
                    >
                    <el-button
                      link
                      plain
                      type="danger"
                      size="small"
                      @click="onDelete(row)"
                      v-if="isDeleteRole"
                      ><el-icon><Delete /></el-icon>删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页器 -->
              <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNo"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
              />
            </el-card>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <el-dialog
      v-model="refuseDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div style="font-weight: bold; margin-bottom: 8px">退回原因</div>
      <el-input
        v-model="refuseReason"
        type="textarea"
        style="width: 300px"
      ></el-input>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSubmitRefuse()">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'

import {
  getContentList,
  getTypeList,
  getContentTree,
  deleteContent,
  submitContent,
  auditCheck,
  auditCheckFalse,
  directFinal,
  proofread
} from '@/api/content/contentList.js'
const router = useRouter()
const route = useRoute()
const store = useStore()
const userId = store.state.app.user.id
const buttonRole = store.state.app.buttonRole
const ids = ref([])
const multiple = ref(true)
const selectWidth = ref('width:200px')
const total = ref()
const coltName = ref('')
const deptTreeRef = ref()
const cid = ref('')
const queryOrderBy = ref('')
const treeDataWithTop = ref([])
const defaultProps = {
  children: 'children',
  label: 'name'
}

// 按钮权限
const isCreateRole = ref(true)
const isUpdateRole = ref(true)
const isDeleteRole = ref(true)
const isSubmitRole = ref(true)
const isExamineRole = ref(true)
const isInstanceRole = ref(true)
// 表格数据
const tableData = ref([])
const typeList = ref([])

// 树
const treeData = ref([])
const searchForm = ref({
  queryId: '',
  queryTitle: '',
  queryTypeId: '',
  queryInputUsername: '',
  releaseDate: '',
  queryStatus: '',
  checkstatus: ''
})

const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})
const refuseDialogVisible = ref(false)
const refuseReason = ref('')

onMounted(() => {
  getTreeList()
  getList()
  getTypeListData()
})

// 模板根目录
const addTopNode = (treeData) => {
  return [
    {
      id: '',
      name: '内容根目录',
      children: treeData
    }
  ]
}

const getTreeList = () => {
  const params = { root: 'source', userId: userId }
  getContentTree({ root: params.root, userId: params.userId }).then((res) => {
    const transArr = res.data.resultlist.map((item) => {
      return {
        id: item.id,
        name: `${item.name}`,
        children: item.children
      }
    })
    treeData.value = transArr
    treeDataWithTop.value = addTopNode(transArr)
  })
}

const copyCellContent = (row, column, cell, event) => {
  // 判断是否是“标题”列
  if (column.property === 'contentExt.title') {
    // 获取单元格内容
    // const text = cell.textContent || cell.innerText
    // 调用复制逻辑
    // copyText(text)
  }
}

// const copyText = async (text) => {
//   try {
//     // 使用原生方法复制
//     navigator.clipboard.writeText(text)
//     ElMessage.success('复制成功')
//   } catch (e) {
//     ElMessage.error('复制失败，请手动复制')
//   }
// }

// 获取列表
const getList = async () => {
  const { status } = route.query
  if (status !== undefined) {
    searchForm.value.queryStatus = status
  }
  // 按钮权限
  buttonRole.map((item) => {
    if ('内容管理'.includes(item.name)) {
      item.children.map((list) => {
        if (list.name === '内容添加') {
          if (list.isbutton) {
            isCreateRole.value = true
          } else {
            isCreateRole.value = false
          }
        }
        if (list.name === '内容修改') {
          if (list.isbutton) {
            isUpdateRole.value = true
          } else {
            isUpdateRole.value = false
          }
        }
        if (list.name === '内容删除') {
          if (list.isbutton) {
            isDeleteRole.value = true
          } else {
            isDeleteRole.value = false
          }
        }
        if (list.name === '内容提交') {
          if (list.isbutton) {
            isSubmitRole.value = true
          } else {
            isSubmitRole.value = false
          }
        }
        if (list.name === '内容审核') {
          if (list.isbutton) {
            isExamineRole.value = true
          } else {
            isExamineRole.value = false
          }
        }
        if (list.name === '内容终审') {
          if (list.isbutton) {
            isInstanceRole.value = true
          } else {
            isInstanceRole.value = false
          }
        }
      })
    }
  })
  await getContentList({
    ...queryParams.value,
    ...searchForm.value,
    releaseDate: searchForm.value.releaseDate
      ? dayjs(searchForm.value.releaseDate).format('YYYY-MM-DD')
      : '',
    userId: userId,
    queryTopLevel: '',
    queryRecommend: '',
    cid: cid.value,
    queryViews: '',
    queryOrderBy: queryOrderBy.value
  })
    .then((res) => {
      total.value = res.data.total
      tableData.value = res.data.list
    })
    .catch((err) => {
      console.log(err)
    })
}
// 获取标签列表
const getTypeListData = async () => {
  await getTypeList()
    .then((res) => {
      typeList.value = res.data
    })
    .catch((err) => {
      console.log(err)
    })
}
// 搜索
const onSearch = () => {
  queryParams.value = {
    pageNo: 1,
    pageSize: 10
  }
  getList()
}

// 重置
const onReset = () => {
  searchForm.value = {
    queryId: '',
    queryTitle: '',
    queryTypeId: '',
    queryInputUsername: '',
    releaseDate: '',
    queryStatus: '',
    checkstatus: ''
  }
}

// 结构树搜索
watch(coltName, (val) => {
  deptTreeRef.value.filter(val)
})

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 添加
const handleAdd = () => {
  router.push('/content/AddContentManagement')
}
// 提交按钮
const handleSubmit = async () => {
  if (ids.value.length > 1) {
    return ElMessage.error('只能选择一条数据提交')
  } else {
    const params = {
      content_id: ids.value[0],
      user_id: userId
    }
    const res = await submitContent(params)
    ElMessage.success(res.message)
    getList()
  }
}
// 校对按钮
const handleProofread = (row) => {
  proofread({ content_id: row.id, user_id: userId }).then((res) => {
    ElMessage.success(res.message)
    getList()
  })
}
// 审核通过
const handlePass = async () => {
  if (ids.value.length > 1) {
    return ElMessage.error('只能选择一条数据提交')
  } else {
    const params = {
      content_id: ids.value[0],
      user_id: userId
    }
    const res = await auditCheck(params)
    ElMessage.success(res.message)
    getList()
  }
}
// 直接终审
const handleInstance = async () => {
  if (ids.value.length > 1) {
    return ElMessage.error('只能选择一条数据提交')
  } else {
    const params = {
      content_id: ids.value[0],
      user_id: userId
    }
    const res = await directFinal(params)
    ElMessage.success(res.message)
    getList()
  }
}
// 审核不通过
const handleNopass = () => {
  if (ids.value.length > 1) {
    return ElMessage.error('只能选择一条数据提交')
  } else {
    refuseDialogVisible.value = true
  }
}
// 不通过
const onSubmitRefuse = async () => {
  const params = {
    content_id: ids.value[0],
    user_id: userId,
    check_opinion: refuseReason.value
  }
  const res = await auditCheckFalse(params)
  ElMessage.success(res.message)
  getList()
  refuseDialogVisible.value = false
}

// 多项删除
const handleAllDelete = () => {
  ElMessageBox.confirm('您确定要删除这些数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteContent(ids.value, { userId }).then((res) => {
        ElMessage.success(res.message)
        getList()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 修改
const onEdit = (row) => {
  router.push({ path: '/content/EditContentManagement', query: { id: row.id } })
}
// 删除
const onDelete = (row) => {
  ElMessageBox.confirm('您确定要删除这条数据吗？', '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteContent([row.id], { userId }).then((res) => {
        ElMessage.success(res.message)
        getList()
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
// 查看
const onPreview = (row) => {
  router.push({ path: './PreviewContentManagement', query: { id: row.id } })
}

const handleNodeClick = async (data) => {
  const { id } = data
  cid.value = id
  await getList()
  cid.value = ''
}
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
  multiple.value = !selection.length
}
// 排序
const handleSortChange = async ({ column, prop, order }) => {
  if (order) {
    queryOrderBy.value = order === 'descending' ? 0 : 1 // 根据实际需求调整值
    await getList()
  }
}
const processedTitle = (title) => {
  return title.replace(/<br\s*\/?>/gi, '')
}
</script>

<style lang="scss" scoped>
.splitpanes {
  .splitpanes__pane {
    background-color: #fff;
  }
  .splitpanes__splitter {
    width: 7px !important;
    border-left: 1px solid #eee;
    background-color: #1d1e1f;
    border-color: #303030;

    &:hover {
      background-color: #2d2d2d;
    }

    &:before,
    &:after {
      background-color: #303030;
    }
  }
}
.buttons {
  text-align: center;
}

:deep(.el-table .el-table__header-wrapper th) {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px !important;
  font-size: 13px;
}
:deep(.el-form .el-form-item label) {
  font-weight: bold !important;
}
:deep(.el-form .el-form-item .el-form-item__label) {
  font-weight: bold !important;
}
:deep(.uploadFile .el-form-item__label) {
  font-weight: bold !important;
}
:deep(.editor .el-form-item__label) {
  font-weight: bold !important;
}
:deep(.el-form-item__content .el-textarea .el-textarea__inner) {
  height: 100px !important;
}

.head-container {
  position: sticky;
  top: 0;
  z-index: 100;
}
</style>
